package io.cloud.tec.project.component;

import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DistributedLock {

    @Autowired
    RedissonClient redissonClient;

    public void getLock(String key, long waitTime, long leaseTime) {
        RLock lock = redissonClient.getLock(key);
        boolean res = false;
        // 第一个参数是等待时间，60秒内获取不到锁，则直接返回。第二个参数是100秒后强制释放
        try {
            // tryLock
            // wait time
//            res = lock.tryLock(100, TimeUnit.SECONDS);
            res = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            // lock
//            lock.lock();
//            lock.lock( 100, TimeUnit.SECONDS);
            if (res) {
                Thread c = Thread.currentThread();
                log.info("线程：{},{},{},{}", waitTime, leaseTime, c.getId(), waitTime, leaseTime);
                TimeUnit.SECONDS.sleep(waitTime);
                // do biz
                return;
            }
            throw new RuntimeException("其他业务正在处理中，请稍等");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (res && lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

//        lock.lock( 100, TimeUnit.SECONDS);
//        lock.lock();
    }


}

@Slf4j
@Configuration
class DistributedLockConfig {

//    @Bean
//    @Lazy
//    RedissonClient redissonClient() {
//        Config config = new Config();
//        config.useSingleServer()
////                .setPassword(")
//                .setAddress("redis://127.0.0.1:6379");
//        log.info("redissonClient");
//        return Redisson.create(config);
//    }

//    @Bean
//    @ConditionalOnMissingBean(name = "redissonClient")
//    RedissonClient clusterRedissonClient() {
//        Config config = new Config();
//        config.useClusterServers()
//                .setPassword("")
//                .setNodeAddresses(Collections.emptyList());
//        log.info("clusterRedissonClient");
//        return Redisson.create(config);
//    }
}
